-
Notifications
You must be signed in to change notification settings - Fork 174
/
laravel-sms.js
98 lines (91 loc) · 3.13 KB
/
laravel-sms.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*
* send verify sms
*---------------------------
* top lan <toplan710@gmail.com>
* https://github.com/toplan/laravel-sms
* --------------------------
* Date 2015/06/08
*/
(function($){
$.fn.sms = function(options) {
var self = this;
var btnOriginContent, timeId;
var opts = $.extend(true, {}, $.fn.sms.defaults, options);
self.on('click', function (e) {
btnOriginContent = self.html() || self.val() || '';
changeBtn(opts.language.sending, true);
send();
});
function send() {
var url = getUrl();
var requestData = getRequestData();
$.ajax({
url : url,
type : 'post',
data : requestData,
success : function (data) {
if (data.success) {
timer(opts.interval);
} else {
changeBtn(btnOriginContent, false);
opts.notify.call(null, data.message, data.type);
}
},
error : function(xhr, type){
changeBtn(btnOriginContent, false);
opts.notify.call(null, opts.language.failed, 'request_failed');
}
});
}
function getUrl() {
return opts.requestUrl ||
'/laravel-sms/' + (opts.voice ? 'voice-verify' : 'verify-code')
}
function getRequestData() {
var requestData = { _token: opts.token || '' };
var data = $.isPlainObject(opts.requestData) ? opts.requestData : {};
$.each(data, function (key) {
if (typeof data[key] === 'function') {
requestData[key] = data[key].call(requestData);
} else {
requestData[key] = data[key];
}
});
return requestData;
}
function timer(seconds) {
var btnText = opts.language.resendable;
btnText = typeof btnText === 'string' ? btnText : '';
if (seconds < 0) {
clearTimeout(timeId);
changeBtn(btnOriginContent, false);
} else {
timeId = setTimeout(function() {
clearTimeout(timeId);
changeBtn(btnText.replace('{{seconds}}', (seconds--) + ''), true);
timer(seconds);
}, 1000);
}
}
function changeBtn(content, disabled) {
self.html(content);
self.val(content);
self.prop('disabled', !!disabled);
}
};
$.fn.sms.defaults = {
token : null,
interval : 60,
voice : false,
requestUrl : null,
requestData : null,
notify : function (msg, type) {
alert(msg);
},
language : {
sending : '短信发送中...',
failed : '请求失败,请重试',
resendable : '{{seconds}} 秒后再次发送'
}
};
})(window.jQuery || window.Zepto);